package umls.geneus.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import umls.geneus.core.sax.PubmedIdParser;

public class UncachedPubmedSearch implements PubmedSearcher{
	private static String  fetchurl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi";
	private static String  searchidhurl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=";
	private static Logger logger;
	public UncachedPubmedSearch(){
	}
	public List<String> searchPubmed(List<String> input) throws IOException{
		String keyword=URLEncoder.encode(input.remove(0),  "UTF-8");
		for (String s : input ){
			keyword+="+"+URLEncoder.encode(s,  "UTF-8");
		}
		URL url = new URL(searchidhurl +keyword+"&retmax=5");
		logger.trace(url);
		InputStream is = (url.openConnection()
				.getInputStream());
		PubmedIdParser pp = new PubmedIdParser();
		SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = null;
		 try {
				saxParser = factory.newSAXParser();
			} catch (ParserConfigurationException e) {
				logger.error("Error: "+e.getMessage());
				e.printStackTrace();
			} catch (SAXException e) {
				logger.error("Error: "+e.getMessage());
				e.printStackTrace();
			}
		 try {
			saxParser.parse(is, pp);
		} catch (SAXException e) {
			logger.error("Error: "+e.getMessage());
			e.printStackTrace();
		}
		 return pp.getIds();
	}
	public String getPubmedAbstract(String id)throws SAXException, IOException {
		
			InputStream is = null;
			URL url = new URL(fetchurl + "?db=pubmed&retmode=xml&id=" + id);
			is = (url.openConnection()
					.getInputStream());
			StringBuilder sb = new StringBuilder();
			  SAXParserFactory factory = SAXParserFactory.newInstance();
              SAXParser saxParser = null;
			 try {
				saxParser = factory.newSAXParser();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 return "ciao";
	}
	
}
